package com.wxscrmplus.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.wxscrmplus.common.core.domain.entity.SysUser;
import com.wxscrmplus.common.utils.StringUtils;
import com.wxscrmplus.common.core.page.TableDataInfo;
import com.wxscrmplus.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wxscrmplus.customer.domain.vo.CustomerVo;
import com.wxscrmplus.customer.mapper.CustomerMapper;
import com.wxscrmplus.customer.service.ICustomerService;
import com.wxscrmplus.statistics.service.ICustomerStatsService;
import com.wxscrmplus.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.wxscrmplus.customer.domain.bo.OpportunityBo;
import com.wxscrmplus.customer.domain.vo.OpportunityVo;
import com.wxscrmplus.customer.domain.Opportunity;
import com.wxscrmplus.customer.mapper.OpportunityMapper;
import com.wxscrmplus.customer.service.IOpportunityService;

import java.util.*;

/**
 * 销售机会Service业务层处理
 *
 * @author 王永超
 * @date 2023-03-26
 */
@RequiredArgsConstructor
@Service
public class OpportunityServiceImpl implements IOpportunityService {

    private final OpportunityMapper baseMapper;
// 2ba914a5e52598d1f7db2b4ddcbd4206
    private final SysUserMapper userMapper;
    private final CustomerMapper customerMapper;
    private final ICustomerService customerService;
    private final ICustomerStatsService customerStatsService;


    /**
     * 查询销售机会
     */
    @Override
    public OpportunityVo queryById(Long opportunityId) {
        OpportunityVo opportunityVo = baseMapper.selectVoById(opportunityId);
        SysUser sysUser = userMapper.selectById(opportunityVo.getSaleId());
        opportunityVo.setSaleName(sysUser.getNickName());
        return opportunityVo;
    }

    /**
     * 查询销售机会列表
     */
    @Override
    public TableDataInfo<OpportunityVo> queryPageList(OpportunityBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Opportunity> lqw = buildQueryWrapper(bo);
        Page<OpportunityVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        for (OpportunityVo record : result.getRecords()) {
            SysUser sysUser = userMapper.selectById(record.getSaleId());
            record.setSaleName(sysUser.getNickName());
            CustomerVo customerVo = customerMapper.selectVoById(record.getCustomerId());
            record.setCustomerName(customerVo.getName());
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询销售机会列表
     */
    @Override
    public List<OpportunityVo> queryList(OpportunityBo bo) {
        LambdaQueryWrapper<Opportunity> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Opportunity> buildQueryWrapper(OpportunityBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Opportunity> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), Opportunity::getName, bo.getName());
        lqw.eq(bo.getCustomerId() != null, Opportunity::getCustomerId, bo.getCustomerId());
        lqw.eq(bo.getSaleId() != null, Opportunity::getSaleId, bo.getSaleId());
        lqw.eq(StringUtils.isNotBlank(bo.getSaleStage()), Opportunity::getSaleStage, bo.getSaleStage());
        lqw.between(params.get("beginPredictMakeTime") != null && params.get("endPredictMakeTime") != null,
            Opportunity::getPredictMakeTime, params.get("beginPredictMakeTime"), params.get("endPredictMakeTime"));
        lqw.in(CollectionUtil.isNotEmpty(bo.getDataRangeUserIds()), Opportunity::getSaleId, bo.getDataRangeUserIds());
        lqw.orderByDesc(Opportunity::getOpportunityId);
        return lqw;
    }

    /**
     * 新增销售机会
     */
    @Override
    public Boolean insertByBo(OpportunityBo bo) {
        Opportunity add = BeanUtil.toBean(bo, Opportunity.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setOpportunityId(add.getOpportunityId());
        }
        customerStatsService.refreshOpportunityAmountByCustomerIds(bo.getCustomerId());
        return flag;
    }

    /**
     * 修改销售机会
     */
    @Override
    public Boolean updateByBo(OpportunityBo bo) {
        Opportunity update = BeanUtil.toBean(bo, Opportunity.class);
        validEntityBeforeSave(update);
        customerStatsService.refreshOpportunityAmountByCustomerIds(bo.getCustomerId());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Opportunity entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除销售机会
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
